package org.icy.core;

import org.ice.http.HttpRequest;
import org.ice.registry.IRegistry;
import org.ice.registry.RegistryFactory;
import org.icy.core.http.IcyHttpRequest;
import org.icy.core.message.Subject;
import org.icy.modules.IcyModule;

public class Bootstrap implements Runnable {
	
	private IcyModule module;
	
	public Bootstrap(IcyModule module) {
		this.module = module;
	}

	public void run() {
		Subject sbj = Subject.getInstance();
		sbj.notifyMessage("ApplicationStart", module);
		_wrapRequest();
		_initSession();
		sbj.notifyMessage("SessionInit", module);
		_initTemplate();
		sbj.notifyMessage("TemplateInit", module);
	}
	
	private void _initSession() {
		module.getRequest().setSession("icy", true);
		module.getRequest().setSession("icy.mode", "run");
	}
	
	private void _initTemplate() {
		HttpRequest hr = module.getRequest();
		IRegistry reg = RegistryFactory.getRegistry();
		if (reg.get("icy.app.install").equals(false)) {
			module.redirect("install", "index");
			return;
		}
		hr.setAttribute("theme", reg.get("icy.app.theme"));
		module.setTemplate("/templates/"+reg.get("icy.app.theme")+"/index.jsp");
	}

	private void _wrapRequest() {
		HttpRequest request = module.getRequest();
		module.setRequest(new IcyHttpRequest(request));
	}
}
